#include <iostream>
#include <string.h>
#include <iomanip>

int main()
{
	int type;
	std::cin >> type;

	int n, m;
	std::cin >> n >> m;
	char vertex[n];

	int charToIndex[128];
	for (int i = 0; i < n; ++i)
	{
		char c;
		std::cin >> c;
		vertex[i] = c;
		charToIndex[c] = i;
	}

	int adjMat[n][n];
	memset(adjMat, 0, n * n * sizeof(int));

	for (int i = 0; i < m; ++i)
	{
		char c1, c2;
		int weight = 1;
		std::cin >> c1 >> c2;
		if (type == 2 || type == 4)
		{
			std::cin >> weight;
		}

		adjMat[charToIndex[c1]][charToIndex[c2]] = weight;
		if (type == 3 || type == 4)
		{
			adjMat[charToIndex[c2]][charToIndex[c1]] = weight;
		}
	}

	for (auto c : vertex)
	{
		std::cout << c << ' ';
	}
	std::cout << std::endl;

	for (int i = 0; i < n; ++i)
	{
		for (int j = 0; j < n; ++j)
		{
			std::cout << std::setw(4) << adjMat[i][j];
		}
		std::cout << std::endl;
	}

	if (type == 1 || type == 3)
	{
		for (auto c : vertex)
		{
			std::cout << c << "-->";
			for (int i = n - 1; i >= 0; --i)
			{
				if (adjMat[charToIndex[c]][i] != 0)
				{
					std::cout << i << ' ';
				}
			}
			std::cout << std::endl;
		}
	}
	else
	{
		for (auto c : vertex)
		{
			std::cout << c << "-->";
			for (int i = n - 1; i >= 0; --i)
			{
				int weight = adjMat[charToIndex[c]][i];
				if (weight != 0)
				{
					std::cout << i << ',' << weight << ' ';
				}
			}
			std::cout << std::endl;
		}
	}

	return 0;
}

